const FlakeId = require('flake-idgen')
const intformat = require('biguint-format')

//字符串工具
const StringUtils = {
  //字符串是否为空
  isEmpty(text) {
    if (!text) {
      return true
    }
    let str = typeof text == 'string' ? text.trim() : text
    return str == "" || !str;
  },
  //字符串不为空
  notEmpty(text) {
    return !this.isEmpty(text);
  },
};
//断言工具
const AssertUtils = {
  BaseError(message = "异常", code = 400) {
    let error = new Error(message);
    error.status = code;
    throw error;
  },
  isTrue(bool, message = "条件不通过", code = 400) {
    if (!bool) {
      this.BaseError(message, code);
    }
  },
  isFalse(bool, message = "条件不通过", code = 400) {
    if (bool) {
      this.BaseError(message, code);
    }
  },
  StringNotEmpty(text, message = "不能为空", code = 400) {
    if (StringUtils.isEmpty(text)) {
      this.BaseError(message, code);
    }
  },
  ObjectNotEmpty(obj, message = "不能为空", code = 400) {
    let type = typeof obj;
    if (type == "undefined" || !obj || obj == null) {
      this.BaseError(message, code);
    }
  },
};

const FieldUtils = {
  BaseFilterObject(obj, arr = [], isIn = false) {
    let objs = {};
    Object.keys(obj)
      .filter((item) => (isIn ? arr.includes(item) : !arr.includes(item)))
      .forEach((key) => (objs[key] = obj[key]));
    return objs;
  },
  //过滤指定字段
  FilterObjectNotIn(obj, arr = []) {
    return this.BaseFilterObject(obj, arr, false)
  },
  //只需要部分字段
  FilterObjectIn(obj, arr = []) {
    return this.BaseFilterObject(obj, arr, true)
  },
};
//随机数工具
const RandomUtils = {
  randomNumber(len) {
    let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    let ran = []
    for (let index = 0; index <= len; index++) {
      ran.push(numbers[Math.floor(Math.random() * numbers.length)])
    }
    return parseInt(ran.join(''))
  },
  //随机数
  random(ranMin, ranMax) {
    let ran = (ranMax - ranMin) + 1
    return parseInt(Math.random() * ran) + ranMin
  }
}
//id生成
const IdUtils = {
  //生成随机id
  flakeId() {
    return (intformat(new FlakeId().next(), 'dec'))
  }
}
module.exports = {
  StringUtils,
  AssertUtils,
  FieldUtils,
  IdUtils,
  RandomUtils
};
